﻿using M_Process.API.Appliction.Command.ReportingCommand;
using M_Process.Domain.DTO;
using M_Process.Repository.ProcessInterface;
using MediatR;

namespace M_Process.API.Appliction.CommandHandlers.ReportingCommandHandler
{
    /// <summary>
    /// 反报工命令处理器
    /// </summary>
    public class ReverseReportingCommandHandler : IRequestHandler<ReverseReportingCommand, ReportingProcessTaskDto>
    {
        /// <summary>
        /// 报工仓储
        /// </summary>
        protected readonly IReportingRepository reportingRepository;

        /// <summary>
        /// 工序任务仓储接口
        /// </summary>
        protected readonly IProcessTasksRepository processTasksRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="reportingRepository">报工仓储</param>
        /// <param name="processTasksRepository">工序任务仓储接口</param>
        public ReverseReportingCommandHandler(IReportingRepository reportingRepository, IProcessTasksRepository processTasksRepository)
        {
            this.reportingRepository = reportingRepository;
            this.processTasksRepository = processTasksRepository;
        }

        /// <summary>
        /// 处理反报工命令
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ReportingProcessTaskDto> Handle(ReverseReportingCommand request, CancellationToken cancellationToken)
        {
            var list = (from a in await reportingRepository.GetAllAsync()
                       join b in await processTasksRepository.GetAllAsync()
                       on a.ProcessTasksId equals b.ProcessTasksId
                       where a.IsDeleted == false && b.IsDeleted == false
                       && a.ReportingId == request.ReportingId
                       select new ReportingProcessTaskDto
                       {
                           ReportingId = a.ReportingId,
                           ReportingNum = a.ReportingNum,
                           ReportingNumber = a.ReportingNumber,
                           EquipmentName = a.EquipmentName,
                           EquipmentNumber = a.EquipmentNumber,
                           Station = a.Station,
                           TeamsAndGroups = a.TeamsAndGroups,
                           ProcessTasksId = b.ProcessTasksId,
                           TaskNumber = b.TaskNumber,
                           ProductionBatch = b.ProductionBatch,
                           ProcessName = b.ProcessName,
                           ProductNumber = b.ProductNumber,
                           Operator = a.Operator,
                           CreatedBy = b.CreatedBy,
                           CreatedDate = b.CreatedDate,
                           IsDeleted = b.IsDeleted
                       }).FirstOrDefault();
            return list;
        }
    }
}
